package com.softwareinlife.gae.sample.datastore;

import java.io.IOException;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.softwareinlife.gae.sample.datastore.model.DeviceModel;
import com.softwareinlife.gae.sample.datastore.model.UserModel;

@SuppressWarnings("serial")
public class OneToManyServlet extends HttpServlet {

	private static final PersistenceManagerFactory pmf =
	        JDOHelper.getPersistenceManagerFactory("transactions-optional");

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		PersistenceManager pm = pmf.getPersistenceManager();
		String id = null;
		UserModel user = null;
		try {
			pm.currentTransaction().begin();
			
			id = req.getParameter("id");
			if (id == null) {
				id = req.getSession().getId();
			}
			
			user = new UserModel(id, "lastName");
			
			user.add(new DeviceModel("type", id));
			user.add(new DeviceModel("type", id));
			
			pm.makePersistent(user);
			
			pm.currentTransaction().commit();

		} finally {
			if (pm.currentTransaction().isActive()) {
				pm.currentTransaction().rollback();
			}
		}
		
		UserModel model = pm.getObjectById(UserModel.class, id);

		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, OneToMany! " + id + " " + model);
	}
}
